﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace ConsolidationTool.WebParts.Layouts.AjaxServices
{
    public class ReceiverServices : IAjaxService
    {
        public AjaxResult Excute(System.Web.HttpContext httpContext, FSSearchEntity searchEntity)
        {
            SPList list = SPContext.Current.Web.Lists.TryGetList(searchEntity.ListTitle);
            SPQuery query = new SPQuery();
            query.Query = string.Format(@"<Where>
      <And>
         <Eq>
            <FieldRef Name='Year' />
            <Value Type='Integer'>{0}</Value>
         </Eq>
         <And>
            <Eq>
               <FieldRef Name='Month' />
               <Value Type='Integer'>{1}</Value>
            </Eq>
            <Eq>
               <FieldRef Name='CoCd' />
               <Value Type='Text'>{2}</Value>
            </Eq>
         </And>
      </And>
   </Where>
 ", searchEntity.Year, searchEntity.Month, searchEntity.CompanyCode);

            string fieldToReceiver = httpContext.Request["fields"];

            string[] fields = fieldToReceiver.Split(',');

            var listItems = list.GetItems(query);
            bool success = listItems.Count > 0;
            string message = "";
            if (success)
            {
                searchEntity.Data = "{";
                var listitem = listItems[0];

                if (fieldToReceiver == "All")
                    foreach (SPField field in listitem.ContentType.Fields)
                    {
                        if (field.StaticName != "Control")
                            searchEntity.Data += string.Format("\"{0}\":\"{1}\",", field.StaticName, listitem[field.StaticName]);
                    }
                else {
                    for (int i = 0; i < fields.Length; i++)
                    {
                        var value = listitem[fields[i]];
                        searchEntity.Data += string.Format("\"{0}\":\"{1}\",", fields[i], value); 
                    }
                }

                searchEntity.Data = searchEntity.Data.Substring(0, searchEntity.Data.Length - 1);
                searchEntity.Data += "}";
            }
            else
            {
                message = "can not find result ...";
            }

            return new AjaxResult(success, searchEntity) { FullMsg = message };

        }
    }
}
